package com.starry.module.system.core.checkcode.service.impl;


import com.starry.module.system.api.checkcode.domain.qo.CaptchaCreateQo;
import com.starry.module.system.api.checkcode.domain.vo.CaptchaVo;
import com.starry.module.system.core.checkcode.properties.CaptchaProperties;
import com.starry.module.system.core.checkcode.service.CaptchaStrategy;
import com.wf.captcha.ArithmeticCaptcha;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @Description 算术验证码
 * @Author xiaoke
 *
 */
@Service("arithmetic_captcha")
public class ArithmeticCaptchaStrategy implements CaptchaStrategy {

    private final CaptchaProperties captchaProperties;

    public ArithmeticCaptchaStrategy(CaptchaProperties captchaProperties) {
        this.captchaProperties = captchaProperties;
    }

    @Override
    public CaptchaVo generateCaptcha(CaptchaCreateQo qo) {
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = "";
        try {
            result = String.valueOf(Double.valueOf(captcha.text()).intValue());
        } catch (Exception e) {
            result = captcha.text();
        }
        return CaptchaVo.builder()
                .img(captcha.toBase64())
                .result(result)
                .key(UUID.randomUUID().toString())
                .build();
    }
}
